<template>
  <div class="manage-container user-manage">
    <div class="search-block">
      <h3>用户管理</h3>
      <div class="flex-row search-filters">
        <div class="flex-row">
          <el-form size="small" :inline="true" :model="formQuery">
            <el-form-item label="账号名称" class="filter">
              <el-input v-model.trim="formQuery.name" placeholder="请输入" maxLength="40" clearable></el-input>
            </el-form-item>
            <el-form-item label="账号" class="filter">
              <el-input v-model.trim="formQuery.mobile" placeholder="请输入" maxLength="40" clearable></el-input>
            </el-form-item>
            <el-form-item label="所属单位" class="filter" v-if="userInfo.role_name === '超级管理员'">
              <el-select v-model="formQuery.unit_name" clearable>
                <el-option
                  v-for="item in dialogRelevant.companyList"
                  :key="item.id"
                  :label="item.unit_name"
                  :value="item.unit_name"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属角色" class="filter">
              <el-select v-model="formQuery.role_name" clearable>
                <el-option v-for="item in roleList" :key="item.name" :label="item.name" :value="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>

        <div class="search-btns">
          <el-button plain @click="clickReset">重置</el-button>
          <el-button type="primary" @click="clickSearch">查询</el-button>
        </div>
      </div>
    </div>

    <div class="user-table">
      <div class="user-table-action">
        <el-button style="background: #1890ff; border: 1px solid #1890ff; color: #fff" plain @click="clickAdd"
          >新建用户</el-button
        >
        <el-button plain @click="clickExport">导出数据</el-button>
      </div>
      <div class="user-table-data">
        <comTable
          :loading="pagination.loading"
          :tableData="userList"
          :listCount="pagination.total"
          :pageSize="pagination.pageSize"
          :currentPage="pagination.currentPage"
          :userColumn="tableColumns()"
          @updatePage="handleCurrentChange"
          @sizePage="handleSizeChange"
        >
          <template #name>
            <el-table-column label="名称" minWidth="80">
              <template #default="scope">
                <span style="color: #1182fb; padding: 0 10px; cursor: pointer">{{ scope.row.name }}</span>
              </template>
            </el-table-column>
          </template>
          <template #action>
            <el-table-column label="操作" minWidth="80">
              <template #default="scope">
                <span style="color: #1182fb; padding: 0 10px; cursor: pointer" @click="handleEdit(scope.row)"
                  >编辑</span
                >
                <span style="color: #ff2a00; padding: 0 10px; cursor: pointer" @click="handleDelete(scope.row)"
                  >删除</span
                >
              </template>
            </el-table-column>
          </template>
        </comTable>
      </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialogRelevant.dialogVisible"
      :title="dialogRelevant.dialogTitle"
      width="25%"
      :modal="false"
      draggable
    >
      <div class="dialog-line"></div>
      <div class="dialog-con">
        <div>
          <el-form
            size="small"
            ref="formRef"
            :rules="dialogRelevant.rules"
            :inline="true"
            :model="dialogRelevant.formDetails"
            label-width="75px"
          >
            <el-form-item label="账号名称" class="filter" prop="name">
              <el-input
                v-model.trim="dialogRelevant.formDetails.name"
                placeholder="请输入用户名"
                maxLength="40"
                :disabled="dialogRelevant.dialogTitle === '编辑'"
              ></el-input>
            </el-form-item>
            <el-form-item label="账号" class="filter" prop="mobile">
              <el-input
                v-model.trim="dialogRelevant.formDetails.mobile"
                placeholder="请输入手机号"
                maxLength="40"
                :disabled="dialogRelevant.dialogTitle === '编辑'"
              ></el-input>
            </el-form-item>
            <el-form-item label="所属单位" class="filter" prop="unit_id" v-if="userInfo.role_name === '超级管理员'">
              <el-select
                v-model="dialogRelevant.formDetails.unit_name"
                filterable
                remote
                :remote-method="remoteMethod"
                placeholder="请选择单位"
                @change="changeCompany($event)"
              >
                <el-option
                  v-for="item in dialogRelevant.companyList"
                  :key="item.id"
                  :label="item.unit_name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="用户角色" class="filter" v-if="dialogRelevant.dialogTitle === '编辑'">
              <el-select v-model="dialogRelevant.formDetails.role_name" @change="changeRoles">
                <el-option v-for="item in roleList" :key="item.role_id" :label="item.name" :value="item.role_id" />
              </el-select>
            </el-form-item>
            <el-form-item label="申请时间" class="filter" v-if="dialogRelevant.dialogTitle === '编辑'">
              <el-input
                v-model.trim="dialogRelevant.formDetails.created_at"
                placeholder="请输入"
                maxLength="40"
                :disabled="true"
              ></el-input>
            </el-form-item>
            <el-form-item label="审核人" class="filter" v-if="dialogRelevant.dialogTitle === '编辑'">
              <el-input
                v-model.trim="dialogRelevant.formDetails.process_user"
                placeholder="无"
                maxLength="40"
                :disabled="true"
              ></el-input>
            </el-form-item>
            <el-form-item label="审核时间" class="filter" v-if="dialogRelevant.dialogTitle === '编辑'">
              <el-input
                v-model.trim="dialogRelevant.formDetails.processed_at"
                placeholder="无"
                maxLength="40"
                :disabled="true"
              ></el-input>
            </el-form-item>
            <el-form-item label="审核人电话" class="filter" v-if="dialogRelevant.dialogTitle === '编辑'">
              <el-input
                v-model.trim="dialogRelevant.formDetails.process_mobile"
                placeholder="无"
                maxLength="40"
                :disabled="true"
              ></el-input>
            </el-form-item>
            <el-form-item label="密码" class="filter" prop="password" v-if="dialogRelevant.dialogTitle === '新建用户'">
              <el-input
                v-model.trim="dialogRelevant.formDetails.password"
                placeholder="初始密码同手机号"
                type="password"
                maxLength="40"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="dialog-line"></div>
      <template #footer>
        <span class="dialog-footer">
          <el-button class="btn-cancel" @click="dialogRelevant.dialogCancel">取消</el-button>
          <el-button class="btn-confirm" type="primary" @click="dialogRelevant.dialogConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 删除确认 -->
    <div class="delete">
      <el-dialog v-model="deleteVisible" :modal="false" width="20%" draggable>
        <span>删除之后要无法撤销，确定要删除吗？ </span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deleteVisible = false" style="margin-right: 20px">取消</el-button>
            <el-button type="primary" @click="deleteConfirm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {reactive, ref, onMounted} from 'vue';
import axios from 'axios';
import {ElMessage} from 'element-plus';
import personalApi from '@/api/personalApi';
import registerApi from '@/api/register.ts';
import comTable from '@/components/comTable/index.vue';
import {validatePassword, validateAccount} from '@/utils/validator.js';

const formQuery = reactive({});
const formRef = ref(null);
const roleList = ref([
  {name: '普通用户', role_id: '3'},
  {name: '单位管理员', role_id: '2'},
  {name: '超级管理员', role_id: '1'},
]);
const id = ref<number>();
const deleteVisible = ref(false);
const userInfo = JSON.parse(localStorage.getItem('userInfo')) || '';
const operationRole = ref('');

const pagination = reactive({
  loading: false,
  total: 20,
  pageSize: 20,
  currentPage: 1,
});
// 重置
const clickReset = () => {
  formQuery.name = '';
  formQuery.unit_name = '';
  formQuery.mobile = '';
  formQuery.role_name = '';
  getUserList();
};
// 查询
const clickSearch = () => {
  getUserList(formQuery);
};
// 新建用户
const clickAdd = () => {
  dialogRelevant.dialogTitle = '新建用户';
  dialogRelevant.dialogVisible = true;
  dialogRelevant.formDetails.name = '';
  dialogRelevant.formDetails.mobile = '';
  dialogRelevant.formDetails.unit_id = '';
  dialogRelevant.formDetails.unit_name = '';
  dialogRelevant.formDetails.password = '';
};
// 导出数据
const clickExport = async () => {
  const exportUrl = `${import.meta.env.VITE_API_URL}/api/user/export`;
  const data = await axios({
    method: 'get',
    url: exportUrl,
    headers: {
      token: localStorage.getItem('token'),
    },
    params: formQuery,
    responseType: 'blob',
  });
  const url = window.URL.createObjectURL(new Blob([data.data]));
  let link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  link.setAttribute('download', '用户列表.xlsx');
  document.body.appendChild(link);
  link.click();
  URL.revokeObjectURL(link.href); // 释放URL 对象
  document.body.removeChild(link);
  link = null;
};
// 详情
const roleId = ref('');
const handleEdit = (item: any) => {
  dialogRelevant.dialogTitle = '编辑';
  dialogRelevant.dialogVisible = true;
  operationRole.value = item.role_name;
  roleId.value = item.id;
  personalApi
    .userManagDetail({id: item.id})
    .then((res) => {
      if (res.status === 0) {
        dialogRelevant.formDetails = {
          name: res.data.name,
          mobile: res.data.mobile,
          unit_id: res.data.unit_id,
          unit_name: res.data.unit_name,
          role_name: res.data.role_name,
          role_id: res.data.role_id,
          created_at: res.data.created_at,
          process_user: res.data.apply && res.data.apply.process_user,
          process_mobile: res.data.apply && res.data.apply.process_mobile,
          processed_at: res.data.apply && res.data.apply.processed_at,
        };
      }
    })
    .catch((err) => {
      throw err;
    });
};
// 删除
const handleDelete = (item: any) => {
  id.value = item.id;
  deleteVisible.value = !deleteVisible.value;
};
const deleteConfirm = () => {
  personalApi
    .userManagDelete({id: id.value})
    .then((res) => {
      if (res.status === 0) {
        ElMessage.success(res.message);
        getUserList({...formQuery});
        deleteVisible.value = !deleteVisible.value;
      }
    })
    .catch((err) => {
      throw err;
    });
};
// 弹窗相关
const dialogRelevant = reactive({
  dialogVisible: false,
  dialogTitle: '',
  formDetails: {},
  companyList: [],
  rules: {
    mobile: [{validator: validateAccount, trigger: 'blur'}],
    name: [{required: true, message: '请输入用户名', trigger: 'blur'}],
    unit_id: [{required: true, message: '请选择单位', trigger: 'change'}],
    password: [{validator: validatePassword, trigger: 'blur'}],
  },
  dialogCancel: () => {
    dialogRelevant.dialogVisible = false;
    formRef.value.clearValidate();
  },
  dialogConfirm: () => {
    if (dialogRelevant.dialogTitle === '编辑') {
      editFnc();
    } else {
      addFnc();
    }
  },
});
// 新增
const addFnc = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (userInfo.role_name !== '超级管理员') {
        dialogRelevant.formDetails.unit_id = userInfo.unit_id;
      }
      personalApi
        .userManagSave({
          name: dialogRelevant.formDetails.name,
          mobile: dialogRelevant.formDetails.mobile,
          password: dialogRelevant.formDetails.password,
          unit_id: dialogRelevant.formDetails.unit_id.toString(),
        })
        .then((res) => {
          if (res.status === 0) {
            ElMessage.success(res.message);
            dialogRelevant.dialogVisible = false;
            getUserList({...formQuery});
          }
        })
        .catch((err) => {
          throw err;
        });
    }
  });
};
// 编辑
const editFnc = () => {
  if (userInfo.role_name !== '超级管理员') {
    dialogRelevant.formDetails.unit_id = userInfo.unit_id;
  }
  if (operationRole.value === '超级管理员' && userInfo.role_name !== '超级管理员') {
    ElMessage.warning('当前用户无此权限');
    return;
  }
  personalApi
    .userManagSave({
      id: roleId.value,
      role_id: dialogRelevant.formDetails.role_id,
      unit_id: dialogRelevant.formDetails.unit_id.toString(),
    })
    .then((res) => {
      if (res.status === 0) {
        ElMessage.success(res.message);
        dialogRelevant.dialogVisible = false;
        getUserList({...formQuery});
      }
    })
    .catch((err) => {
      throw err;
    });
};
// 选择角色
const changeRoles = (e) => {
  dialogRelevant.formDetails.role_id = e;
};
// 选择单位
const changeCompany = (e) => {
  dialogRelevant.formDetails.unit_id = e;
};

// 获取单位列表
const getCompanyList = () => {
  registerApi
    .getCompanyList()
    .then((res) => {
      dialogRelevant.companyList = res.data;
    })
    .catch((err) => {
      throw err;
    });
};
// 搜索单位列表
const remoteMethod = (query: string) => {
  if (query) {
    registerApi
      .getCompanyList({keyword: query})
      .then((res) => {
        dialogRelevant.companyList = res.data;
      })
      .catch((err) => {
        throw err;
      });
  } else {
    dialogRelevant.companyList = [];
  }
};
// 列表数据
const userList = ref([]);
const getUserList = (params) => {
  pagination.loading = true;
  personalApi
    .userManagList({...params, per_page: pagination.pageSiz, page: pagination.currentPage})
    .then((res) => {
      if (res.status === 0) {
        userList.value = res.data.data;
        pagination.total = res.data.total;
        pagination.pageSize = res.data.per_page;
        pagination.currentPage = res.data.current_page;
        pagination.loading = false;
      }
    })
    .catch((err) => {
      throw err;
    });
};

// 翻页相关
const handleSizeChange = (e: any) => {
  pagination.pageSiz = e.pageSize;
  getUserList({...formQuery});
};
const handleCurrentChange = (e: any) => {
  pagination.currentPage = e.currentPage;
  getUserList({...formQuery});
};

onMounted(() => {
  getUserList();
  getCompanyList();
  if (userInfo.role_id !== 1) {
    roleList.value.splice(2, 1);
  }
});
// 表格表头
const tableColumns = () => [
  {
    prop: 'name',
    label: '账号名称',
    slot: 'name',
  },
  {
    prop: 'mobile',
    label: '账号',
    minWidth: 80,
  },
  {
    prop: 'unit_name',
    label: '所属单位',
    minWidth: 150,
  },
  {
    prop: 'role_name',
    label: '用户角色',
    minWidth: 100,
  },
  {
    prop: 'created_at',
    label: '创建时间',
    minWidth: 160,
  },
  {
    prop: 'action',
    label: '操作',
    slot: 'action',
  },
];
</script>
<style lang="scss" scoped>
@import url('@/assets/css/manage.scss');
.user-manage {
  background-color: transparent;
  padding: 0;
  &:deep(.el-dialog__body) {
    padding: 0;
  }
  &:deep(.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before) {
    content: '' !important;
  }
  .dialog-con {
    .el-form {
      display: flex;
      flex-direction: column;
      padding: 24px 48px;
    }
    .el-form-item {
      margin-top: 25px;
    }
    .el-input {
      width: 280px;
    }
    .el-select {
      width: 280px;
      &:deep(.el-input--suffix) {
        width: 280px;
      }
    }
    &:deep(.el-form-item__label) {
      margin-right: 34px;
      text-align: right !important;
    }
  }
}
.search {
  &-block {
    height: 125px;
    background-color: #fff;
    padding: 20px 30px;
    border-radius: 2px;
  }
  &-filters {
    margin-top: 20px;
    justify-content: space-between;
    color: #333333;
    font-size: 14px;
    .el-input {
      margin-left: 15px;
      width: 172px;
      height: 32px;
    }
    .el-select {
      margin-left: 15px;
      width: 172px;
      height: 32px;
    }
    .filter {
      margin-right: 40px;
    }
  }
  &-btns {
    align-self: end;
    align-content: flex-end;
  }
}

.dialog-line {
  height: 1px;
  background: rgba(0, 0, 0, 0.06);
}
.user-table {
  height: calc(100% - 175px);
  box-sizing: border-box;
  padding: 30px;
  background-color: #fff;
  margin-top: 14px;
  overflow: hidden;
  &-action {
    display: flex;
    justify-content: end;
  }
  &-data {
    height: calc(100% - 20px);
  }
}
.delete {
  &:deep(.el-dialog__body) {
    padding: 24px;
  }
}
@media only screen and (max-width: 1366px) and (min-width: 768px) {
  .user-manage {
    &:deep(.el-dialog) {
      width: 35% !important;
    }
  }
}
</style>
